package com.shanzmoo.h5.web;

import com.alipay.api.AlipayApiException;
import com.shanzmoo.base.bean.SHttpResponse;
import com.shanzmoo.base.bean.SResponse;
import com.shanzmoo.core.domain.pay.WxWapPayResp;
import com.shanzmoo.db.mall.service.IMallOrderService;
import com.shanzmoo.h5.domain.OrderPayResult;
import com.shanzmoo.h5.domain.req.PayOrderByAliWebReq;
import com.shanzmoo.h5.domain.req.PayOrderByWxJsapReq;
import com.shanzmoo.h5.domain.req.PayOrderByWxMwebReq;
import com.shanzmoo.h5.manager.TradeManager;
import com.shanzmoo.h5.util.SecurityUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 交易服务
 * @author Gzhao 2021/1/2
 */
@Slf4j
@RestController
@RequestMapping("order/trade")
@Api(tags = "交易服务")
public class TradeController {

    @Autowired
    private TradeManager tradeManager;

    @ApiOperation("支付宝网页支付")
    @GetMapping("aliPay/byWap")
    public void aliPayByWap(HttpServletResponse response, PayOrderByAliWebReq request) throws AlipayApiException,
            IOException {
        String form = tradeManager.tradeByAliWap(request);

        response.setContentType("text/html;charset=UTF-8");
        //直接将完整的表单html输出到页面
        response.getWriter().write(form);
        response.getWriter().flush();
        response.getWriter().close();
    }

    @ApiOperation("微信JSAP支付（公众号h5）")
    @PostMapping("wxPay/byJsap")
    public SHttpResponse<WxWapPayResp> wxPayByJsap(@RequestBody PayOrderByWxJsapReq request) {
        Integer memberId = SecurityUtil.getCurrentMemeberId();
        SResponse<WxWapPayResp> re = tradeManager.tradeBywxJsapPay(memberId, request);
        return SHttpResponse.transform(re);
    }

    @ApiOperation("微信网页支付（非微信浏览器）")
    @PostMapping("wxPay/byMweb")
    public SHttpResponse<String> wxPayByMweb(@RequestBody PayOrderByWxMwebReq request) {
        SResponse<String> re = tradeManager.wxPayByMweb(request);
        return SHttpResponse.transform(re);
    }

    @ApiOperation("查询支付结果")
    @GetMapping("pay/result")
    public SHttpResponse<OrderPayResult> queryPayResult(@RequestParam String orderNo) {
        SResponse<OrderPayResult> re  = tradeManager.queryPayResult(orderNo);
        return SHttpResponse.transform(re);
    }
}
